package TAIC.feature;

import java.util.List;
import TAIC.kdtree.KDTree;

public class Match {
	public static double NN_RATIO = 0.49 ;
	
	static public void match ( double [][] source, double[][] target, Node matchCount[] ) throws Exception {
		KDTree kdtree = new KDTree < Integer > ( target[0].length ) ;
		for ( int i = 0 ; i < target.length ; i ++ 	) {
			try {
				kdtree.insert( target [i], i ) ;
			}catch( Exception e){}
		}
		for ( int i = 0 ; i < source.length ; i ++ ) {
			List<Integer> result = kdtree.nearest( source[i], 2 ) ;
			int n1 = result.get(0);
			int n2 = result.get(1);
			double dist1 = dist ( source [i], target [n1]) ;
			double dist2 = dist ( source [i], target [n2]) ;
			if ( dist2 < dist1 * NN_RATIO ) matchCount [ i ].value ++ ;
		}
	}	
	
	static public double dist ( double p[], double q[]) {
		double result = 0;
		double diff ;
		for ( int i = 0 ; i < p.length ; i ++ ) {
			diff = p [ i ] - q [ i ] ; 
			result += diff * diff; 
		}
		return result ;
	}
}
